import React from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import { PhotoSwipe, Tools } from 'weaver-mobile';

const f = v => v.replace(/<a([^<]+)<\/a>/g, m => `<a target="_blank" ${m.slice(3)}`);

export default class ContentIframe extends React.Component {
  static filter = f;
  static defaultProps = {
    prefixCls: 'email-view',
    mobilesrc: Tools.mobileDetect(),
  }

  constructor(props) {
    super(props);
    this.isInstanceMounted = false;
    this.id = `emailContentIframe_${Math.random().toString(36).substr(2, 6)}`;
    this.state = {
      height: 0,
      width: 0,
      scale: 0,
      frameStyle: {},
      loadIframe: true,
      loading: false,
      imgList: [],
      imgIndex: 0,
      imgVisible: false,
    };
    props.fun(true)
  }

  componentDidMount() {
    this.isInstanceMounted = true;
    const { value } = this.props;
    this.setContent(value, true);
  }

  componentWillReceiveProps(nextProps) {
    const { value: _value } = this.props;
    const { value } = nextProps;
    if (_value !== value) {
      // need reload iframe and reset height twice to set body height auto
      this.setState({ loadIframe: false, height: 0 }, () => {
        this.setState({ loadIframe: true, height: 0 }, () => {
          this.setContent(value, _value !== value);
        });
      });
    }
  }

  componentDidUpdate() {
    const frame = this.refs.content;
    const win = frame.contentWindow;
    const doc = win.document;
    let tags = doc.getElementsByTagName('a'); 
    let docLength = tags.length;
    for (let i=0; i<docLength; i++) {
      if (tags[i]) {
        tags[i].onclick = (e) => {
          e.preventDefault();
          const href = tags[i].href
          href && window.openLink(href);
        }
      }
    }
  }

  componentWillUnmount() {
    this.isInstanceMounted = false;
  }

  getWidth = () => {
    const frame = this.refs && this.refs.content;
    // width 在IOS下获取有失误，问题后续跟踪
    const win = frame&&frame.contentWindow;
    const doc = win&&win.document;
    let scrollWidth = doc&&doc.getElementById('contentIframe').scrollWidth;
    let offsetWidth = doc&&doc.getElementById('contentIframe').offsetWidth;
    let width = scrollWidth || offsetWidth;

    return width;
  }

  setContent(value, init) {
    const { contentLoading, imgReg } = this.props;
    const frame = this.refs.content;
    const win = frame.contentWindow;
    const doc = win.document;
    if (typeof value === 'string') {
      init && doc.write('<html><head></head><body id="contentIframe" style="overflow-y:hidden"></body></html>');
      doc.body.innerHTML = f(value);
    }
    // get height while imgs all loaded
    const imgs = doc.getElementsByTagName('img');
    let imgLoaded = 0;
    let imgList = [];
    this.setState({ loading: true });
    const onOk = () => {
      imgLoaded ++;
      if (!contentLoading && value === '' || (imgLoaded === imgs.length || !imgReg)) {
        const { fun } = this.props;
        const { scrollHeight = 0, offsetHeight = 0, scrollWidth, offsetWidth } = doc.getElementById('contentIframe');
        this.setState({
          width: (scrollWidth || offsetWidth),
          height: (scrollHeight || offsetHeight),
          loading: false,
        }, this.zoomIframe);
        fun(false);
      }
    };
    !imgs || imgs.length === 0 ? onOk()
    : Array.prototype.forEach.call(imgs, (img, index) => {
      if (img.src) {
        img.onload = (e) => {
          if(img.src.indexOf('data:image/gif')===-1) { // 过滤掉base64:gif图片
            imgList.push({
              url: img.currentSrc,
              w: img.naturalWidth,
              h: img.naturalHeight,
            });
          }
          onOk();
        }
        if(img.src.indexOf('data:image/gif')===-1) { // 过滤掉base64:gif的图片
          img.onclick = (e) => {
            this.setState({ imgIndex: index, imgVisible: true });
            let targetIndex = this.getArrIndex(imgList, e.target.currentSrc)
            PhotoSwipe.showImage(imgList, targetIndex);
          }
        }
        img.onerror = onOk;
      } else {
        onOk()
      }
    });
    this.setState({ imgList });
  }

  getArrIndex = (Arr, url) => {
    let aimIndex = 0;
    Arr.map((v, index) => {
      if (url.indexOf(v.url) > -1 || url === v.url) {
        aimIndex = index;
      }
      return 0;
    })
    return aimIndex;
  }
  
  zoomIframe = () => {
    const frame = ReactDOM.findDOMNode(this.refs.content);
    const parentWidth = frame.parentNode.offsetWidth;
    const width = this.getWidth();
    if (width > parentWidth * 5) {
      this.props.changeZoom(false)
    }
    const scale = Math.floor(parentWidth * 100/width)/100;
    this.setState({
      frameStyle: {
        transform: `scale(${scale})`,
        transformOrigin: '0 0',
        transition:"transform 500ms ease-out",
      },
      scale: scale,
    });
  }

  render() {
    const { prefixCls, isZoom } = this.props;
    const { height, loadIframe, frameStyle, scale } = this.state;
    const width = this.getWidth();
    const divStyle = {
      width: '100%',
      height: loadIframe ? ((scale && isZoom) ? height * scale : height) : 'auto',
      overflow: loadIframe ? 'hidden':'auto'
    };
    const divCls = classnames({
      [`${prefixCls}-content-iframecontainer`]: !isZoom
    })
    let iframeStyle = {
      width: loadIframe ? width : '100%',
      minWidth: '100%',
      height: loadIframe ? height : 'auto',
    }
    if (isZoom) iframeStyle = {...frameStyle, ...iframeStyle}
    return (
      <div className={divCls} style={divStyle}>
        <iframe
          id={this.id}
          title='contentIframe'
          ref='content'
          className={`${prefixCls}-content-iframe`}
          style={iframeStyle}
        />
      </div>
    );
  }
}
